package com.choosefine.it.common.conf;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * @Author Ye_Wenda
 * @Date 2016/12/8 0008
 */
@Component
public class MongoToolComponent {

    private static final Logger logger = LoggerFactory.getLogger(MongoToolComponent.class);

    @Autowired
    private MongoTemplate mongoTemplate;

    public Long getSequence() {
        return this.getSequence(null);
    }

    public Long getSequence(String className) {
        if (StringUtils.isEmpty(className)) {
            className = Sequence.class.getName();
        }
        Query query = new Query(Criteria.where("name").is(className));
        Update update = new Update().inc("globalSequence", 1);
        Sequence sequence = mongoTemplate.findAndModify(query, update, Sequence.class);
        if (sequence == null) {
            sequence = new Sequence(1L, className);
            mongoTemplate.save(sequence);
            return 1L;
        } else {
            return sequence.getGlobalSequence() + 1;
        }
    }

    class Sequence {

        private String id;

        private Long globalSequence;

        private String name;

        public Sequence(Long globalSequence, String name) {
            this.globalSequence = globalSequence;
            this.name = name;
        }

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public Long getGlobalSequence() {
            return globalSequence;
        }

        public void setGlobalSequence(Long globalSequence) {
            this.globalSequence = globalSequence;
        }
    }
}
